package top.withwings.bonus.bonus.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import top.withwings.bonus.bonus.pojo.BonusForm;
import top.withwings.bonus.bonus.service.BonusFormService;
import top.withwings.bonus.common.pojo.PageParam;
import top.withwings.bonus.common.pojo.PagedData;
import top.withwings.bonus.common.pojo.UnixTimestampToDateEditor;

import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping("bonusForm")
public class BonusFormController {

    @Autowired
    private BonusFormService bonusFormService;


    @PostMapping("page")
    public PagedData<BonusForm> page(PageParam pageParam, Date startDate, Date endDate, Integer salesmanId) {

        return bonusFormService.getBonusFormPage(pageParam, salesmanId, startDate, endDate);
    }


    @PostMapping("create")
    public void create(@RequestBody BonusForm bonusForm) {
        bonusForm.resetComputation();
        bonusForm.setAmount(bonusForm.getPrice() * bonusForm.getQuantity());
        bonusFormService.create(bonusForm);
    }

    @PostMapping("update")
    public void update(@RequestBody BonusForm bonusForm){
        bonusForm.resetComputation();;
        bonusForm.setAmount(bonusForm.getPrice() * bonusForm.getQuantity());
        bonusFormService.update(bonusForm);
    }

    @PostMapping("delete")
    public void delete(int id){
        bonusFormService.delete(id);
    }


    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //时间戳转date
        binder.registerCustomEditor(Date.class, new UnixTimestampToDateEditor());
    }


}
